/*
 * Copyright 2025-2026 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package glz.hawk.springboot.jooq.poc;

import org.jooq.DSLContext;
import org.jooq.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.jooq.impl.DSL.*;

/**
 * This class is responsible for
 *
 * @author Zhang Peng
 */
@Component
public class Simple {

    @Autowired
    private DSLContext create;

    public String getQuerySql() {
        // Fetch a SQL string from a jOOQ Query to manually execute it with another tool.
        // For simplicity reasons, we're using the API to construct case-insensitive object references, here.
        Query select = create.select(field("BOOK.TITLE").bitNot().minus(100).as("title"), field("AUTHOR.FIRST_NAME"), field("AUTHOR.LAST_NAME"),
                create.select(field("A1")).from(table("T1")).asField("Col1"))
            .from(table("BOOK"))
            .join(table("AUTHOR"))
            .on(field("BOOK.AUTHOR_ID").eq(field("AUTHOR.ID")))
            .where(field("BOOK.PUBLISHED_IN").eq(1948), or(field("AUTHOR.LAST_NAME").eq("1948")))
            .orderBy(field("BOOK.TITLE").desc(), field("AUTHOR.FIRST_NAME").asc())
            .limit(1);

        String selectSql = select.getSQL();
        System.out.println("**********************************");
        System.out.println(selectSql);

//        Query insert = create.insertInto(table("BOOK"))
//            .set(field("BOOK_ID"), 100)
//            .set(field("BOOK_NAME"), "Hello");
        Query insert = create.insertInto(table("BOOK"),field("BOOK_ID").as("bookId"), field("BOOK_NAME"),field("BOOK_TYPE"))
            .values(field("BOOK_ID").as("bookId"), field("BOOK_NAME"), field("BOOK_TYPE"));
        String insertSql = insert.getSQL();
        System.out.println("**********************************");
        System.out.println(insertSql);

        StringBuilder sb = new StringBuilder();
        sb.append(selectSql).append("<br>").append(insertSql);
        return sb.toString();
    }

    public String getInsertSql() {
        return create.insertInto(table("AUTHOR"))
            .set(field("BOOK.TITLE"), "1")
            .getSQL();

    }

}
